package com.gxa.hotel.portal.jms;


import com.gxa.hotel.core.pojo.domain.Hotel;
import com.gxa.hotel.portal.service.impl.GoodsCacheServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

@Component
@Slf4j
public class GoodsCacheListener {

    @Autowired
    GoodsCacheServiceImpl goodsCacheService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate=null;

    private static final String HOTEL="hotel:detail";
    /**
     * ActiveMQ的简单监听机制
     * @param id
     */
//    @JmsListener(destination = "goodsCache")
//    public void getGoodsCacheId(String id){
//
//        //业务逻辑:
//        //接收到id消息表示该商品被后台修改了信息
//        //接下来,从redis中删除对应的缓存
//        //
//        String key=GoodsCacheServiceImpl.GOODS_CACHE+id;
//
//        Boolean success = redisTemplate.delete(key);
//        log.info("编号为{}的商品缓存的删除结果:{}",id,success);
//    }

    /**
     *  @JmsListener 配置了containerFactory属性,表示通过自定义的容器工厂加载JmsTemplate
     *  该容器工厂配置了事务和签收机制
     *  注入消息对象的时候,采用消息原本的状态,message
     *
     *  ActiveMQ的消息ID唯一,RabbitMQ的消息id每次都不同
     *  所以,Rabbit得用UUID作唯一性的判断
     * @param message 消息队列传输的Message对象
     * @param session
     * @throws JMSException
     */
    @JmsListener(destination = "hotelCache",containerFactory = "containerFactory")
    public void getGoodsCacheId(Message message, Session session) throws JMSException {
        ActiveMQObjectMessage objectMessage = (ActiveMQObjectMessage) message;
      // 获取要删除的缓存商品的编号
      //  Object id = objectMessage.getObject();
        //监听到该操作之后就执行删除,不管有没有数据
        Boolean delete = redisTemplate.delete(HOTEL);
       message.acknowledge();

    }
    @JmsListener(destination = "createHotGoods",containerFactory = "containerFactory")
    public void createHotGoods(Message message, Session session) throws JMSException {
        ActiveMQObjectMessage objectMessage = (ActiveMQObjectMessage) message;
// 获取要删除的缓存商品的编号
        Object id = objectMessage.getObject();
        try {
            //先通过id查数据库商品信息
            goodsCacheService.selectGoodsCache((Long) id);

            //再签收
            message.acknowledge();
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }
}
